package aorey.database.config;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class DataConfigInsert {

    // 数据表名
    public String name = "";
    // 数据源名称
    public String data_source = "";
    // 功能名称
    public String class_name = "";
    // 模块名称
    public String method_name = "";
    // 数据表字段
    public List<DataConfigField> fields ;

    public DataConfigInsert(String config) throws DocumentException {
        File configFile = new File(config);
        if (configFile.exists()) {
            SAXReader reader = new SAXReader();
            Document document = reader.read(configFile);
            Element node = document.getRootElement();
            Element tabNode = node.elements().get(0);
            List<Element> fieldsElements = tabNode.elements();
            this.name = tabNode.attributeValue("name");
            this.data_source = tabNode.attributeValue("data_source");
            this.class_name = tabNode.attributeValue("class");
            this.method_name = tabNode.attributeValue("method");
            this.fields = new ArrayList<>();
            int size = fieldsElements.size();
            for (int i = 0; i < size; i++) 
            {
                DataConfigField dataConfigField = new DataConfigField();
                dataConfigField.name = fieldsElements.get(i).attributeValue("name");
                dataConfigField.type = fieldsElements.get(i).attributeValue("type");
                dataConfigField.scope= fieldsElements.get(i).attributeValue("scope");
                dataConfigField.id = fieldsElements.get(i).attributeValue("id");
                dataConfigField.allow_null = fieldsElements.get(i).attributeValue("null");
                dataConfigField.errortext = fieldsElements.get(i).attributeValue("errortext");
                try
                {
                    dataConfigField.len = Integer.parseInt(fieldsElements.get(i).attributeValue("len"));
                } catch (Exception e)
                {
                    dataConfigField.len = 0;
                }
                this.fields.add(dataConfigField);
                dataConfigField = null;
            }
        }
        else
        {
            System.out.println("文件不存在！");
        }
    }
}
